package com.ceadeal.auth.util;

import com.ceadeal.auth.config.custom.CustomUserDetails;
import com.ceadeal.auth.entity.User;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

/**
 * 功能描述: 认证用户工具类
 * <p>
 * 作者: Yzw
 * 日期: 2017-03-03 10:05:10
 */
public class OAuth2Util {

    /**
     * 认证是否通过
     * @return
     */
    public static Boolean isAuthenticated() {
        return SecurityContextHolder.getContext().getAuthentication().isAuthenticated();
    }

    /**
     * 获取认证用户信息
     * @return
     */
    public static User getUser() {
        if (!isAuthenticated()) {
            return null;
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = null;
        if (principal instanceof UserDetails) {
            CustomUserDetails userDetails = (CustomUserDetails) principal;
            user = userDetails.getExtUserInfo();
        }
        return user;
    }

    /**
     * 获取Token值
     * @return
     */
    public static String getTokenValue() {
        String tokenValue = null;
        Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
        if (null != details && details instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails oDetails = (OAuth2AuthenticationDetails) details;

            tokenValue = oDetails.getTokenValue();
        }
        return tokenValue;
    }

    /**
     * 获取带token类型的请求头字符串（如：Bearer <tokenValue></tokenValue>）
     * @return
     */
    public static String getBearerTokenValue() {
        String tokenValue = null;
        Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
        if (null != details && details instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails oDetails = (OAuth2AuthenticationDetails) details;

            tokenValue = oDetails.getTokenType() + " " + oDetails.getTokenValue();
        }
        return tokenValue;
    }
}
